package com.meilishuo.message.entity.common;

import java.util.Date;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j;

import org.eclipse.jetty.util.log.Log;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;

import com.alibaba.fastjson.JSON;
import com.meilishuo.message.exceptions.BadRequestException;
import com.meilishuo.message.exceptions.ResourceNotFoundException;
import com.meilishuo.message.exceptions.ServiceException;
import com.meilishuo.message.exceptions.WarningException;


/**
 * The general operation result for every action.
 * 
 */
@Log4j
@Getter
@Setter

public class GeneralResult {
	private int returnCode = 0;
	private String message = "success";
	private Date date = new Date();
	private Object result;
//	private List<FieldErrorVO> errors;
	
	// 0 成功，1失败
	public enum ReturnCode {
		Success, Failure
	}

	public void setException(java.lang.Throwable ex) {
		if (ServiceException.class.isInstance(ex) || BadRequestException.class.isInstance(ex) || ResourceNotFoundException.class.isInstance(ex)) {
			if (ex.getMessage() != null) {
				this.message = ex.getMessage();
			} else if (ex.getCause() != null) {
				this.message = ex.getCause().getMessage();
			}
			this.returnCode = ReturnCode.Failure.ordinal();
		} else if (BindException.class.isInstance(ex)) {
			this.message = ((BindException) ex).getAllErrors().get(0)
					.getDefaultMessage();
//			this.errors = FieldErrorVO.convert2FieldErrorVOs(((BindException) ex).getAllErrors());
			this.returnCode = ReturnCode.Failure.ordinal();
		} else if (MethodArgumentNotValidException.class.isInstance(ex)) {
			this.message = ((MethodArgumentNotValidException)ex).getBindingResult().getAllErrors().get(0).getDefaultMessage();
//			this.errors = FieldErrorVO.convert2FieldErrorVOs(((MethodArgumentNotValidException)ex).getBindingResult().getAllErrors());
			this.returnCode = ReturnCode.Failure.ordinal();
		}else if(WarningException.class.isInstance(ex)){
			if (ex.getMessage() != null) {
				this.message = ex.getMessage();
			} else if (ex.getCause() != null) {
				this.message = ex.getCause().getMessage();
			}
			this.message = "Warning: " + this.message;
			this.returnCode = ReturnCode.Success.ordinal();
		}
		else {
			this.message = "系统发生未知错误,请稍后再试";
		}
		
		log.info(JSON.toJSONString(this));
	}

	public static class Builder {
		private GeneralResult result = new GeneralResult();

		public Builder setResult(Object data) {
			result.setResult(data);
			return this;
		}

		public Builder setException(Exception e) {
			result.setException(e);
			return this;
		}

		public GeneralResult getResponse() {
			return result;
		}
	}

	public static Builder newBuilder() {
		return new Builder();
	}
}
